import './App.css'
import SearchNote from './components/SearchNote'
import NoteList, { NoteType } from './components/NoteList'
import { Form, LoaderFunctionArgs, Outlet, ScrollRestoration, useLoaderData, useNavigation } from 'react-router-dom'

export const loader = async ({ request }: LoaderFunctionArgs) => {
	const url = new URL(request.url)
	const res = await fetch(`/api/notes?${url.searchParams}`)
	const notes = await res.json()
	return {
		notes,
		term: url.searchParams.get('term') || ''
	}
}

const App = () => {
	// 获取loader的数据
	const { notes } = useLoaderData()

	// idle, submitting, loading
	const navigation = useNavigation()

	return (
		<div className='container'>
			<aside className='sidebar'>
				<h1 className='logo'>我的笔记本</h1>
				<SearchNote />
				<Form action='notes/new'>
					<button type='submit' className='addNoteBtn'>
						添加笔记
					</button>
				</Form>
				<NoteList notes={notes} />
			</aside>

			<main className='mainContent'>
				{navigation.state === 'loading' && <progress className='loadingProgress' />}
				<Outlet />
				<ScrollRestoration
					getKey={location => {
						return location.pathname
					}}
				></ScrollRestoration>
			</main>
		</div>
	)
}

export default App
